<!-- eslint-disable vue/multi-word-component-names -->
<!-- eslint-disable vue/no-unused-vars -->
<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <div id="commodity" >
         <div>
           <el-card class="box-card">
             <el-row :gutter="20">
               <el-col :span=8>
                   <el-input
                       placeholder="请输入商品名称内容进行查询"
                       v-model="commodityName"
                       clearable>
                   </el-input>
               </el-col>
               <el-col :span=1.5>
                   <el-button type="primary" @click="queryCommodityByName">查询</el-button>
               </el-col>
               <el-col :span=1.5>
                   <el-button v-power functionCode="commodity:add" type="success" @click="openCommodityAddWindow">添加未上架商品</el-button>
               </el-col>
           </el-row>
           <el-table
           :data="commodityData"
           border
           style="width: 100%">
           <el-table-column
             prop="imageId"
             label="商品主图"
             width="100">
             <template slot-scope="scope">
              
              <el-image
                  style="width: 100px height: 100px"
                  :src="'http://101.43.223.224:8765/image/getImageById?id='+scope.row.imageId.split(',')[0]"
                  ></el-image>
          </template>
            </el-table-column>
            <el-table-column
             prop="imageViewId"
             label="商品详情图"
             width="100">
             <template slot-scope="scope">
              <el-image
                  style="width: 100px height: 100px"
                  :src="'http://101.43.223.224:8765/image/getImageById?id='+scope.row.imageViewId.split(',')[0]"
                  ></el-image>
          </template>
            </el-table-column>
            <el-table-column
             prop="commodityName"
             label="商品名称"
             width="150">
            </el-table-column>
            <el-table-column
             prop="price"
             label="商品原价（元）"
             width="80">
             </el-table-column>
             <el-table-column
             prop="favorablePrice"
             label="商品现价（元）"
             width="80">
             </el-table-column>
             <el-table-column
             prop="vipPrice"
             label="vip价格（元）"
             width="80">
             </el-table-column>
             <!-- <el-table-column
             prop="typeId"
             label="商品类型"
             width="100">
             </el-table-column> -->
             <el-table-column
             prop="goodsQuantity"
             label="库存数量"
             width="100">
             </el-table-column>
             <el-table-column
             prop="back"
             label="商品描述"
             width="200">
             </el-table-column>
             <el-table-column
             prop="createTime"
             label="创建时间"
             width="160">
             </el-table-column>
             <el-table-column
             prop="updateTime"
             label="修改时间"
             width="160">
             </el-table-column>
           <el-table-column
           fixed="right"
           label="操作"
           >
               <template slot-scope="scope">
                 <!-- <el-button   @click="openCommodityInfoWindow(scope.row)"  type="primary" size="small">查看</el-button> -->
                 <el-button v-power functionCode="commodity:update"  @click="openupCommodityInfoWindow(scope.row)"  type="success" size="small">编辑</el-button>
                 <el-button v-power functionCode="commodity:delete"  @click="delCommodityInfo(scope.row)" type="success" size="small">上架</el-button>
                 <el-button v-power functionCode="commodity:delete"  @click="delCommodityInfo2(scope.row)" type="danger" size="small">删除</el-button>
               </template>
             </el-table-column>
           </el-table>
           <el-pagination
           @size-change="handleSizeChange"
           @current-change="handleCurrentChange"
           :current-page="1"
           :page-sizes="[10, 20, 30, 40]"
           :page-size="10"
           layout="total, sizes, prev, pager, next, jumper"
           :total="total">
         </el-pagination>
       </el-card>
       <el-dialog
         title="商品编辑"
         :visible.sync="openUpdatewindows"
         @close="updateclose"
         width="35%">
         <el-form :model="openupdate" :rules ="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="商品主图" >
      <el-upload
       list-type="picture-card"
        class="upload-demo"
        :file-list="fileList2"
        :on-remove="afileremove2"
        :before-upload="auploadbefore2">
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="商品介绍图片" >
      <el-upload
        list-type="picture-card"
        class="upload-demo"
        :on-remove="bfileremove2"
        :file-list="jsfileList2"
        :before-upload="buploadbefore2">
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>
            <el-form-item label="姓名" prop="commodityName">
               <el-input v-model="openupdate.commodityName"></el-input>
             </el-form-item>
             <el-form-item label="商品原价" prop="price">
               <!-- <el-input v-model="openupdate.price"></el-input> -->
               <el-input-number v-model="openupdate.price" :step="1" step-strictly></el-input-number>
             </el-form-item>
             <el-form-item label="商品现价" prop="favorablePrice">
               <!-- <el-input v-model="openupdate.favorablePrice"></el-input> -->
               <el-input-number v-model="openupdate.favorablePrice" :step="1" step-strictly></el-input-number>
             </el-form-item>
             <el-form-item label="vip价格" prop="vipPrice">
               <!-- <el-input v-model="openupdate.vipPrice"></el-input> -->
               <el-input-number v-model="openupdate.vipPrice" :step="1" step-strictly></el-input-number>
             </el-form-item>
             <el-form-item label="商品介绍" prop="back">
               <el-input v-model="openupdate.back"></el-input>
             </el-form-item>
             <el-form-item label="类型" prop="typeId">
               <!-- <el-input v-model="openupdate.typeId"></el-input> -->
               <el-select v-model="openupdate.typeId" filterable placeholder="请选择">
              <el-option
              v-for="item in options2"
              :key="item.id" 
              :label="item.typeSname"
              :value="item.id+''">
              </el-option>
              </el-select>
             </el-form-item>
             <el-form-item label="库存数量" prop="goodsQuantity">
              <el-input-number v-model="openupdate.goodsQuantity" :step="1" step-strictly></el-input-number>
               <!-- <el-input v-model=""></el-input> -->
             </el-form-item>
           </el-form>
           <span slot="footer" class="dialog-footer">
             <el-button @click="openUpdatewindows = false">取 消</el-button>
             <el-button type="primary" @click="update('ruleForm')">确 定</el-button>
           </span>
         </el-dialog>
           <!--  查看详细信息  -->
      <el-dialog title="信息" :visible.sync="commodityInfoWindow" width="40%">
        <el-form :model="commodityB" :disabled="true" label-width="100px" class="demo-ruleForm">
      <el-form-item label="图片" >
        <template slot-scope="scope" >
             <el-image style="width: 100px; height: 100px" :src="'getImageById?id='+commodityB.imageId"></el-image>
        </template>
      </el-form-item>
         <el-form-item label="商品名称" prop="commodityName">
           <el-input :value="commodityB.commodityName"></el-input>
         </el-form-item>
         <el-form-item label="电话" prop="commodityPrice">
           <el-input :value="commodityB.commodityPhone"></el-input>
         </el-form-item>
          <el-form-item label="备注" prop="back">
               <el-input v-model="commodityB.back"></el-input>
             </el-form-item>
       </el-form>
     </el-dialog>
   <el-dialog
     title="商品添加"
     :visible.sync="dialogVisible"
     width="35%">
     <el-form :model="commodityForm" :rules ="rules" ref="ruleForm" label-width="100px">
       <!-- 添加图片 -->
    <el-form-item label="商品主图" >
      <el-upload
      action="123123123"
      list-type="picture-card"
        class="upload-demo"
        :file-list="fileList1"
        :on-remove="afileremove"
        :before-upload="auploadbefore">
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="商品介绍图片" >
      <el-upload
      list-type="picture-card"
        class="upload-demo"
        :on-remove="bfileremove"
        :file-list="jsfileList1"
        :before-upload="buploadbefore">
        <i class="el-icon-plus"></i>
      </el-upload>
    </el-form-item>
        <el-form-item label="商品名称" prop="commodityName">
         <el-input v-model="commodityForm.commodityName"></el-input>
        </el-form-item>
        <el-form-item label="商品原价" prop="price">
          <!-- <el-input v-model="commodityForm.price" ></el-input> -->
          <el-input-number v-model="commodityForm.price" :step="1" step-strictly></el-input-number>
        </el-form-item>
        <el-form-item label="商品现价" prop="favorablePrice">
          <!-- <el-input v-model="commodityForm.favorablePrice"></el-input> -->
          <el-input-number v-model="commodityForm.favorablePrice" :step="1" step-strictly></el-input-number>
        </el-form-item>
        <el-form-item label="商品vip价格" prop="vipPrice">
          <!-- <el-input v-model="commodityForm.vipPrice"></el-input> -->
          <el-input-number v-model="commodityForm.vipPrice" :step="1" step-strictly></el-input-number>
        </el-form-item>
        <el-form-item label="库存数量" prop="goodsQuantity">
          <el-input-number v-model="commodityForm.goodsQuantity" :step="1" step-strictly></el-input-number>
        </el-form-item>
        <el-form-item label="商品类型" prop="typeId">
          <!-- <el-input v-model="commodityForm.typeId"></el-input> -->
        <el-select v-model="commodityForm.typeId" filterable placeholder="请选择">
          <el-option
            v-for="item in options2"
            :key="item.id"
            :label="item.typeSname"
            :value="item.id">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="商品介绍" prop="back">
          <el-input v-model="commodityForm.back"></el-input>
        </el-form-item>
       </el-form>
       <span slot="footer" class="dialog-footer">
         <el-button @click="dialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
       </span>
     </el-dialog>
         </div>
       </div>
   </template>
<script>
// 创建商品名信息组件
export default {

  data () {
    return {
      filter:[],
      adelfilelist:[],
      bdelfilelist:[],
      fileList1:[],
      jsfileList1:[],
      fileList2:[],
      jsfileList2:[],
      options2:[],
      total: 0, // 总数量
      openupdate: [],
      commodityInfoWindow: false, // 查看窗口
      commodityB: {}, // 定义
      commodityName: '', // 商品名
      imageUrl: '',
      imageFile: null,
      imageId: '',
      commodityData: [{
      }],
      openUpdatewindows: false,
      dialogVisible: false,
      disabled: false,
      dialogImageUrl: '',
      commodityForm: {
        id: '',
        commodityName: '',
        price: '',
        favorablePrice: '',
        vipPrice: '',
        typeId: '',
        back:'',
        imageId:null,
        imageViewId:null,
        goodsQuantity:''
      },
      rules: {
        commodityName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在1到20个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' },
        ],
        favorablePrice: [
          { required: true, message: '请输入优惠价格名称', trigger: 'blur' },
        ],
        vipPrice: [
          { required: true, message: '请输入vip价格', trigger: 'blur' },
        ],
        typeId: [
          { required: true, message: '请输入类型id', trigger: 'blur' },
        ],
        back: [
          { required: true, message: '请输入商品介绍', trigger: 'blur' },
        ],
        goodsQuantity: [
          { required: true, message: '请输入库存数量', trigger: 'blur' },
        ],
      }
    }
  },
  mounted () { // 页面加载的时候所加载的方法
    // 初始化页面数据
    this.queryCommodityByName()
  },
  methods: {
        // 类型下拉框回显
        handleSelect2 (c) {
      this.commodityForm.id = c.id
    },
    querySearch2 (queryString, cb) {
      const restaurants = this.options2
      console.log(this.options2)
      const results = queryString ? restaurants.filter(this.createFilter2(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter2 (queryString) {
      return (restaurant) => {
        return (restaurant.typeSname.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    updateclose(){
      this.fileList2=[]
              this.jsfileList2=[]
    },
    afileremove(file,filelist){
      for(var a in this.fileList1){
        if(this.fileList1[a].uid == file.uid){
          this.fileList1.splice(parseInt(a),parseInt(a)+1)
        }
      }

    },
    bfileremove(file,filelist){
      for(var a in this.jsfileList1){
        if(this.jsfileList1[a].uid == file.uid){
          this.jsfileList1.splice(parseInt(a),parseInt(a)+1)
        }
      }
    },
    afileremove2(file,filelist){
      if(file.file==undefined){
        this.adelfilelist.push(file.id)
      }
      for(var a in this.fileList2){
        if(this.fileList2[a].uid == file.uid){
          this.fileList2.splice(parseInt(a),parseInt(a)+1)
        }
      }

    },
    bfileremove2(file,filelist){
      if(file.file==undefined){
        this.bdelfilelist.push(file.id)
      }
      for(var a in this.jsfileList2){
        if(this.jsfileList2[a].uid == file.uid){
          this.jsfileList2.splice(parseInt(a),parseInt(a)+1)
        }
      }
    },
    auploadbefore(file){
      console.log(file)
      this.fileList1.push({url:URL.createObjectURL(file),file:file})
      return false
    },
    auploadbefore2(file){
      console.log(file)
      this.fileList2.push({url:URL.createObjectURL(file),file:file})
      return false
    },
    buploadbefore2(file){
      console.log(file)
      this.jsfileList2.push({url:URL.createObjectURL(file),file:file})
      return false
    },
    buploadbefore(file){
      console.log(file)
      this.jsfileList1.push({url:URL.createObjectURL(file),file:file})
      return false
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.queryCommodityByName()
    },
    handleCurrentChange (val) {
      this.pageNum = val
      this.queryCommodityByName()
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
        return false
      }
      this.imageFile = file
      this.imageUrl = URL.createObjectURL(file)
      return false
    },
    // 修改
    update(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // debugger
          const formData = new FormData()
          if (this.fileList2.length !=0) {
            console.log(this.fileList2)
            for(var a in this.fileList2){
              if(this.fileList2[a].file!=undefined){

                formData.append('goodsImg', this.fileList2[a].file, this.fileList2[a].file.fileName)
              }
            }
          }
          if (this.jsfileList2.length !=0) {
            for(var a in this.jsfileList2){
              if(this.jsfileList2[a].file!=undefined){
              
                formData.append('viewImg', this.jsfileList2[a].file, this.jsfileList2[a].file.fileName)
              }
            }
          }
          this.adelfilelist.forEach(a => {
            var c = []
            for(var b in this.openupdate.imageId){
              if(a!=this.openupdate.imageId[b]){
                c.push(this.openupdate.imageId[b])
              }
            }
            this.openupdate.imageId = c
          })

          this.bdelfilelist.forEach(a => {
            var c = []
            for(var b in this.openupdate.imageViewId){
              if(a!=this.openupdate.imageViewId[b]){
                c.push(this.openupdate.imageViewId[b])
              }
            }
            this.openupdate.imageViewId = c
          })
          formData.set('id', this.openupdate.id)
          formData.set('commodityName', this.openupdate.commodityName)
          formData.set('price', this.openupdate.price)
          formData.set('back', this.openupdate.back)
          formData.set('favorablePrice', this.openupdate.favorablePrice)
          formData.set('vipPrice', this.openupdate.vipPrice)
          formData.set('typeId', this.openupdate.typeId)
          formData.set('imageId', this.openupdate.imageId)
          formData.set('imageViewId', this.openupdate.imageViewId)
          formData.set('goodsQuantity', this.openupdate.goodsQuantity)
          // eslint-disable-next-line no-undef
          // console.log(this.$refs.ruleForm)
          this.$axios.post('Commodity/publishCommodityUpdate',
            formData
          ).then(res => {
            if (res.status === 200) {
              this.myMessage('success', '恭喜你，修改成功！')
              this.openUpdatewindows = false // 关闭窗口
              // this.fileList2=[]
              // this.jsfileList2=[]
              this.formData = {
                id: '',
                commodityName: '',
                back:'',
                price: '',
                favorablePrice: '',
                vipPrice: '',
                typeId: '',
                goodsQuantity:''
              }
              this.imageFile = null
              this.queryCommodityByName()// 全查刷新
            }
          }).catch(err => {
            this.myMessage('warning', '对不起，保存失败，请完善未填信息或者稍后再试')
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    delCommodityInfo (id) { // 上架商品名信息
      this.$confirm('此操作将上架该商品信息，是否继续？', '提示', {
        cofirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        // eslint-disable-next-line no-undef
        this.$axios.delete('Commodity/delCommodityById1?id=' + id.id
        ).then(res => {
          if (res.status === 200) {
            this.myMessage('success', '上架成功！')
            this.queryCommodityByName()
          } else {
            this.myMessage('warning', '上架失败！')
          }
        }).catch(res => {
          this.myMessage('error', '上架失败，请联系管理员！')
        })
      }).catch(() => {
        this.myMessage('info', '已取消上架')
      })
    },
    delCommodityInfo2 (id) { // 删除未上架商品名信息
      this.$confirm('此操作将删除该商品信息，是否继续？', '提示', {
        cofirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        // eslint-disable-next-line no-undef
        this.$axios.delete('Commodity/delCommodityById2?id=' + id.id
        ).then(res => {
          if (res.status === 200) {
            this.myMessage('success', '删除成功！')
            this.queryCommodityByName()
          } else {
            this.myMessage('warning', '删除失败！')
          }
        }).catch(res => {
          this.myMessage('error', '删除失败，请联系管理员！')
        })
      }).catch(() => {
        this.myMessage('info', '已取消删除')
      })
    },
     // 通过商品名称查询商品信息
    queryCommodityByName () {
      this.$axios.get('Commodity/getCommodityByPage1',
        {
          params: {
            commodityName: this.commodityName,
            pageSize: this.pageSize,
            pageNum: this.pageNum
          }
        }
      ).then(res => {
        this.commodityData = res.data.data.content
        console.log(this.commodityData)
        this.total = res.data.data.totalSize
      }).catch(err => {
        console.log(err)
      })
    },
    saveCommodityInfo () { // 保持信息
    },
    openCommodityAddWindow () { // 打开新增窗口
      this.dialogVisible = true
      this.imageUrl = ''
            // 类型下拉框
        this.$axios.get('Commodity/getTypeName').then(res => {
        this.options2 = res.data.data
        console.log(this.options2)
      }).catch(err => {
        console.log(err)
      })
    },
    openCommodityInfoWindow (row) { // 打开查看窗口
      this.commodityInfoWindow = true
      this.commodityB = row
    },
    // 修改查看窗口
    openupCommodityInfoWindow (row) { 
           // 类型下拉框
           this.$axios.get('Commodity/getTypeName').then(res => {
        this.options2 = res.data.data
        console.log(this.options2)
      }).catch(err => {
        console.log(err)
      })
      //多图片
      this.fileList2 = []
      this.jsfileList2 = []
      this.openUpdatewindows = true
      this.openupdate = JSON.parse(JSON.stringify(row))
      this.openupdate.imageId = this.openupdate.imageId.split(',')
      this.openupdate.imageViewId = this.openupdate.imageViewId.split(',')
      this.openupdate.imageId.forEach(a => {
        this.fileList2.push({
          url: 'http://101.43.223.224:8765/image/getImageById?id='+a,
          id:a
        })
      })
      this.openupdate.imageViewId.forEach(b => {
        this.jsfileList2.push({
          url: 'http://101.43.223.224:8765/image/getImageById?id='+b,
          id:b

        })
      })
      // this.openupdate= row
    },
    // 添加
    submitForm (formName) {
      console.log(this.$refs.ruleForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // eslint-disable-next-line no-undef
          const formData = new FormData()
          if (this.fileList1.length !=0) {
            for(var a in this.fileList1){
              formData.append('goodsImg', this.fileList1[a].file, this.fileList1[a].file.fileName)
            }
          }
          if (this.jsfileList1.length !=0) {
            for(var a in this.jsfileList1){
              formData.append('viewImg', this.jsfileList1[a].file, this.jsfileList1[a].file.fileName)
            }
          }
          formData.set('commodityName', this.commodityForm.commodityName)
          formData.set('price', this.commodityForm.price)
          formData.set('back', this.commodityForm.back)
          formData.set('favorablePrice', this.commodityForm.favorablePrice)
          formData.set('vipPrice', this.commodityForm.vipPrice)
          formData.set('typeId', this.commodityForm.typeId)
          formData.set('goodsQuantity', this.commodityForm.goodsQuantity)
          this.$axios.post('Commodity/publishCommodityAdd1',
            formData
          ).then(res => {
            if (res.status === 200) {
              this.myMessage('success', '恭喜你，添加成功！')
              this.dialogVisible = false // 关闭窗口
              this.fileList1=[]
              this.jsfileList1=[]
              this.commodityForm = {
                id: '',
                commodityName: '',
                back:'',
                price: '',
                favorablePrice: '',
                vipPrice: '',
                typeId: '',
                goodsQuantity:''
              }
              this.queryCommodityByName()// 全查刷新
            }
          }).catch(err => {
            this.myMessage('warning', '对不起，保存失败，请稍后再试')
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    myMessage (type, message) {
      this.$message({
        message: message,
        type: type
      })
    }
  }
}
</script>

